<template>
  <div class="page">
    <div class="content">
      <div>
        <el-table-form ref="form" class="merge-item">
          <el-form-item label="所属机构:" prop="ckOrgSNNo">
            <el-tree-select
              v-model="query.ckOrgSNNo"
              :clearable="false"
              class="tree-select"
              :popover-width="360"
              :select-params="{
                clearable: true,
                placeholder: '请选择',
                loading: $loadingPlugin.getTreeData,
              }"
              :tree-params="{
                'expand-on-click-node': false,
                'highlight-current': true,
                'filterable': true,
                props: {
                  value: 'orgSNNo',
                  label: 'orgName',
                  disabled: 'disabled',
                },
                data: treeData,
              }"
              @node-click="selectTreeChange"
            />
          </el-form-item>
          <el-form-item :table-form-merge="0.2">
            <el-checkbox v-model="query.option" label="包含下级" />
          </el-form-item>
          <el-form-item label="安检时间:" :table-form-merge="2">
            <el-date-picker
              v-model="date"
              type="daterange"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
            />
          </el-form-item>

          <el-form-item label="处理人:" prop="ckUserName">
            <el-select v-model="query.ckUserIdList" filterable clearable multiple collapse-tags placeholder="请选择">
              <el-option
                v-for="item in checkUserMap"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="merge-item">
            <el-select v-model="qtype" style="width: 180px; margin-right: 2px;">
              <el-option label="关联订单号" value="orderCode" />
              <el-option label="联系电话" value="csmPhone" />
              <el-option label="客户编号" value="csmCode" />
              <el-option label="客户名称" value="csmName" />
              <!-- <el-option label="客户地址" value="csmAddress" /> -->
              <el-option label="安检单号" value="checkId" />
            </el-select>
            <el-input v-model.trim="param" clearable placeholder="请输入" />
          </el-form-item>
          <el-form-item label="安检类型:">
            <el-select v-model="query.checkType" filterable clearable placeholder="请选择">
              <el-option
                v-for="item in checkTypeMap"
                :key="item.value"
                :label="item.desc"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="客户类型:" :table-form-merge="1">
            <el-select
              v-model="query.csmTypes"
              multiple
              placeholder="请选择"
            >
              <el-option
                v-for="item in customerTypeMap"
                :key="item.value"
                :label="item.desc"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户所属机构:" prop="orgSNNo">
            <el-tree-select
              v-model="query.orgSNNo"
              :clearable="false"
              class="tree-select"
              :popover-width="360"
              :select-params="{
                clearable: true,
                placeholder: '请选择',
                loading: $loadingPlugin.getTreeData,
              }"
              :tree-params="{
                'expand-on-click-node': false,
                'highlight-current': true,
                'filterable': true,
                props: {
                  value: 'orgSNNo',
                  label: 'orgName',
                  disabled: 'disabled',
                },
                data: treeData,
              }"
              @node-click="selectTreeChange2"
            />
          </el-form-item>

          <template v-slot:btns>
            <el-button
              v-permission="[60103, 1]"
              type="primary"
              icon="el-icon-search"
              :loading="$loadingPlugin.fetchData"
              @click="search"
            >查询</el-button>
          </template>
        </el-table-form>
        <div style="margin-bottom: 10px;" class="btn-group">
          <el-button
            v-permission="[60103, 2]"
            type="primary"
            icon="el-icon-download"
            :loading="$loadingPlugin.batchExp"
            @click="batchExp"
          >导出</el-button>
        </div>
      </div>
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        v-el-height-adaptive-table="{ bottomOffset: 10 }"
        class="table"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="tableData.column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        custom-column
        @fetch="fetchData"
      />
      <order-details
        ref="orderDetail"
        :payment-method-map="paymentMethodMap"
        :pay-status-map="payStatusMap"
        :transactor-list="transactorList"
        :order-flag-map="orderFlagMap"
        :order-source-map="orderSourceMap"
        :order-status-map="orderStatusMap"
      />
    </div>
    <csm-detail ref="csmDetail" :parent-fetch-data="refresh" :tree-data="treeData" :calc-type-list="calcTypeList" :paymen-fil-list="paymentMethodMap" />
  </div>
</template>

<script>
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { formatColumnMap, parseTime } from '@/utils'
  import {
    userByOrgidQuery,
    queryExportDomain,
    csDeliverUserList,
    gascheckNohouseSelect,
    gascheckNohouseExport,
    queryMap,
    queryTransactorList,
    presetDicQueryList
  } from '@/api'
  import OrderDetails from '../../orderCenter/orderManage/components/OrderDetails.vue'
  import CsmDetail from '../../components/CsmDetailModal/index.vue'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'

  export default {
    name: 'noCheckReason',
    components: {
      OrderDetails, CsmDetail
    },
    data() {
      return {
        qtype: 'csmPhone',
        param: '',
        treeData: [],
        currentOrg: null,
        exportDomain: '',
        currentGoodsType: null,
        SalesmanNameMap: [],
        calcTypeList: [],
        customerTypeMap: [],
        natureList: [],
        checkUserMap: [],
        checkTypeMap: [
          { value: 1, desc: '随单安检', key: 'SD' },
          { value: 2, desc: '定期安检', key: 'JH' }
        ],
        reasonMap: [],
        date: [new Date().setTime(new Date().getTime() - 3600 * 1000 * 24 * 15), new Date()],
        query: {
          checkDt: '',
          checkDtEnd: '',
          ckUserIdList: '',
          checkType: '',
          csmTypes: '',
          ckOrgSNNo: '001000000000000000000',
          option: false
        },
        tableData: {
          total: 0,
          column: [
            {
              type: 'index',
              width: 30
            },
            {
              label: '单号',
              prop: 'nohouseId',
              width: 110
            },
            {
              label: '处理人',
              prop: 'ckUserName'
            },
            {
              prop: 'driverName',
              label: '大车司机',
              showOverflowTooltip: true
            },
            {
              prop: 'escortName',
              label: '押运员',
              showOverflowTooltip: true
            },
            { label: '客户名称', prop: 'csmName', width: 100 },
            {
              label: '客户编号',
              prop: 'csmCode',
              width: 100,
              render: (h, { row }) => <el-link underline={false} onClick={() => this.openCsmDetail(row)}>{row.csmCode}</el-link>
            },
            {
              label: '客户类型',
              prop: 'csmType',
              width: 100,
              render: (h, { row }) => (
              <span>
                {row.csmType &&
                  formatColumnMap(
                    this.customerTypeMap,
                    'value',
                    row.csmType,
                    'desc'
                  )}
              </span>
            )
            },
            {
              label: '安检类型',
              prop: 'checkType',
              minWidth: 110,
              render: (h, { row }) => (
              <span>
                {row.checkType &&
                  formatColumnMap(
                    this.checkTypeMap,
                    'value',
                    row.checkType,
                    'desc'
                  )}
              </span>
            )
            },
            { label: '所属机构', prop: 'ckOrgName', width: 150 },
            { label: '联系电话', prop: 'csmPhone', minWidth: 110 },
            {
              label: '安检时间',
              prop: 'createTime',
              minWidth: 130,
              render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              label: '关联订单',
              prop: 'orderCode',
              minWidth: 110,
              render: (h, { row }) => <el-link underline={false} onClick={() => this.openOrderDetail(row)}>{row.orderCode}</el-link>
            },
            { label: '客户地址', prop: 'csmAddress', width: 300 },
            {
              label: '未安检原因',
              showOverflowTooltip: true,
              prop: 'reason',
              minWidth: 110,
              render: (h, { row }) => (
              <span>
                {row.checkType &&
                  formatColumnMap(
                    this.reasonMap,
                    'value',
                    row.reason,
                    'desc'
                  )}
              </span>
            )
            },
            { label: '备注', prop: 'remark', width: 120 }
          ],
          data: []
        },
        orderStatusMap: [],
        orderSourceMap: [],
        payStatusMap: [],
        paymentMethodMap: [],
        orderFlagMap: [],
        transactorList: []
      }
    },
    computed: {
      ...mapGetters(['orgList', 'corpSettingData'])
    },
    created() {
      this.getTreeData()
      this.getExportDomain()
      this.queryOptionsMap()
      this.queryOptions()
      this.getTransactorList()
    },
    methods: {
      async fetchData({ currentPage, pageSize }) {
        if (this.selectTimeDay === '') {
          this.$message({
            message: '请输入天数！',
            type: 'warning'
          })
          return
        }
        const query = {
          ...this._getQuery(this.query),
          pageIndex: currentPage,
          pageSize
        }
        if (this.param) {
          query[this.qtype] = this.param
        }
        if (this.date && this.date.length > 0) {
          query.checkDt = this.date[0]
          query.checkDtEnd = this.date[1]
        }
        if (query.checkDt && query.checkDtEnd) {
          let checkDt = parseTime(query.checkDt, '{y}-{m}-{d} {h}:{i}:{s}')
          let checkDtEnd = parseTime(query.checkDtEnd, '{y}-{m}-{d} {h}:{i}:{s}')
          checkDt = checkDt.split(' ')
          checkDtEnd = checkDtEnd.split(' ')
          checkDt[1] = '00:00:00'
          checkDtEnd[1] = '00:00:00'
          checkDt = checkDt.join(' ')
          checkDtEnd = checkDtEnd.join(' ')
          query.checkDt = checkDt
          query.checkDtEnd = checkDtEnd
        }
        const res = await gascheckNohouseSelect(query)
        this.tableData.data = res.data.rows
        this.tableData.total = res.data.total
      },
      getSalesmanName(orgId) {
        userByOrgidQuery({
          orgId: orgId,
          corpparm1: 0,
          utype: 64
        }).then(res => {
          this.SalesmanNameMap = res.data
        })
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        query.ckOrgId = this.query.option ? 0 : this.query.ckOrgId
        return query
      },
      // 获取组织机构数据
      // async getTreeData01() {
      //   const res = await organizationQueryList({})
      //   const data = res.data.map(item => ({
      //     label: item.orgName,
      //     ...item
      //   }))
      //   this.treeData01 = getTreeData(data)
      // },
      // 获取组织机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
        this.query.ckOrgSNNo = this.orgList && this.orgList[0].orgSNNo
        this.query.ckOrgId = this.orgList && this.orgList[0].orgId
        // this.getCheckUser(this.orgList[0])
        this.selectTreeChange(this.orgList[0])
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.query.ckOrgId = value.orgId
        this.getCheckUser(value)
        this.$nextTick(() => {
          this.$refs.lbTable.fetch({ currentPage: 1 })
        })
      },
      // 用户所属机构
      selectTreeChange2(value) {
        this.$nextTick(() => {
          this.$refs.lbTable.fetch({ currentPage: 1 })
        })
      },
      // 安检人
      async getCheckUser(val) {
        this.query.ckUserIdList = []
        const res = await csDeliverUserList({
          deliveryOrgId: val.orgId,
          deliveryOrgSNNo: val.orgSNNo,
          utypeList: [2048, 16384]
        })
        this.checkUserMap = res.data
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain).then(res => {
          console.log(res)
          this.exportDomain = res.data
        })
      },
      batchExp() {
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const currentPage = this.$refs.lbTable.currentPage
          const pageSize = this.$refs.lbTable.pageSize
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          const query = {
            ...this._getQuery(this.query),
            currentPage,
            pageSize
          }
          if (this.param) {
            query[this.qtype] = this.param
          }
          if (this.date && this.date.length > 0) {
            query.checkDt = this.date[0]
            query.checkDtEnd = this.date[1]
          }
          gascheckNohouseExport({
            paramInfo: query,
            kv: str // 表格列
          }).then(res => {
            window.open(
              `${this.exportDomain}/page/export/frame?key=${res.data}`,
              '_blank'
            )
          })
        })
      },
      async queryOptions() {
        const res = await presetDicQueryList({ keyFun: 300 })
        if (res.data.length) {
          res.data.forEach(item => {
            this.reasonMap.push({
              value: item.keyId,
              desc: item.keyName
            })
          })
        }
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4, res5, res7, res8] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'ReStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderSource' }),
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' })
        ])
        this.orderStatusMap = res1.data.filter((item) => item.value !== 6) // 订单类型(去掉‘已转派’)
        this.orderFlagMap = res2.data // 订单类型
        this.customerTypeMap = res3.data // 订单类型
        this.payStatusMap = res4.data // 支付状态
        this.paymentMethodMap = res5.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 2048) // 支付方式
        this.orderSourceMap = res7.data // 订单来源
        this.calcTypeList = res8.data
      },
      // 获取下单人列表
      async getTransactorList() {
        const res = await queryTransactorList({})
        this.transactorList = res.data
      },
      async openOrderDetail(row) {
        row.ownerId = row.ckUserId
        await this.$refs.orderDetail.open(row)
      },
      // 打开客户详情弹窗
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      refresh() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      }
    }
  }
</script>

<style lang="scss" scoped>
.page {
  display: flex;
  padding: 0;
  .content {
    width: 0;
    padding: 0 10px 0 10px;
    flex: 1;
    .cus-input {
      /deep/.el-input__inner {
        width: 95px;
      }
    }
  }
  .form {
    margin-left: 10px;
  }
}

/deep/.el-select__tags {
  overflow: hidden;
  span {
    display: flex;
  }
}
.merge-item {
  /deep/.el-input .el-input-group__append:last-child {
    border: 1px solid #DCDFE6;
  }
}
</style>
